package com.suredy.app.porject.ctrl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.model.Dictionary;
import com.suredy.core.mvc.model.MessageModel;
import com.suredy.core.service.DictionarySrv;

/**
 * 字典视图控制器
 * 
 * @author VIVID.G
 * @since 2015-11-4
 * @version v0.1
 */
@Controller
@RequestMapping("/config/dictionary")
public class DictionaryCtrl extends BaseCtrl {

	@Autowired
	private DictionarySrv dictionarySrv;

	@RequestMapping(value = "/list/{groupCode}", method = RequestMethod.GET)
	public String list(@PathVariable String groupCode, Model model) {
		String view = "app/dictionary/list";

		if (StringUtils.isBlank(groupCode))
			return view;

		model.addAttribute("groupCode", groupCode);
		model.addAttribute("data", this.dictionarySrv.getDics(groupCode, null));

		return view;
	}

	@RequestMapping(value = "/add-form/{groupCode}", method = RequestMethod.GET)
	public String createForm(@PathVariable String groupCode, Model model) {
		String view = "app/dictionary/dic-add";

		if (StringUtils.isBlank(groupCode))
			return view;

		model.addAttribute("groupCode", groupCode);

		return view;
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String editForm(@PathVariable String id, Model model) {
		String view = "app/dictionary/dic-edit";

		if (StringUtils.isBlank(id))
			return view;

		model.addAttribute("data", this.dictionarySrv.get(id));

		return view;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Object addDictionary(Dictionary dic) {
		if (dic == null || StringUtils.isBlank(dic.getGroupCode()) || StringUtils.isBlank(dic.getVal()))
			return new MessageModel(false, "无效字典信息！", null);

		dic = this.dictionarySrv.saveOrUpdate(dic);

		if (dic == null || StringUtils.isBlank(dic.getId()))
			return new MessageModel(false, "保存字典信息失败！", null);

		return new MessageModel(true, "保存成功", dic);
	}

	@RequestMapping(value = "/del", method = RequestMethod.POST)
	@ResponseBody
	public Object delDictionary(@RequestParam("ids[]") String[] ids) {
		if (ids == null || ids.length <= 0)
			return MessageModel.createErrorMessage("操作失败，请勾选需要删除的项！", null);

		if (!this.dictionarySrv.delete(ids))
			return MessageModel.createErrorMessage("操作失败，删除数据未成功！", null);

		return MessageModel.createSuccessMessage("操作成功！", null);
	}

}
